<?php
/**
 * 热门小区模型
 */

namespace app\admin\model;


use app\common\lib\RespCode;
use app\common\model\BaseModel;
use custom\Err;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;

class HotVallige extends BaseModel {

    /**
     * 新增/删除 热门小区
     * @param $params
     * @return bool
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws PDOException
     */
    public static function hotStatus($params, $type) {
        Db::startTrans();
        $city_code = $params['city_code'];
        $region_data = Db::name('region')->where('city_code', $city_code)->find();
        $codes = $region_data['p_codes'] . $city_code . ',';
        if (!db("house_village")
            ->where('id', $params['id'])
            ->where('city_codes', 'like',$codes . '%')
            ->find()) {
            Err::add('小区不存在');
            return false;
        }
        if ($type == 0) {
            //取消热门
            self::where('village_id', $params['id'])->delete();
            Db::commit();
            return true;
        } else {
            //设置热门
            $data1 = db("hot_vallige")
                ->where('city_code', $params['city_code'])
                ->select();
            if (count($data1) >= 6) {
                Err::add('热门推荐小区最多6个');
                return false;
            }
            if (empty(db("hot_vallige")
                ->where('village_id', $params['id'])
                ->select())) {
                $name = db("house_village")
                    ->where('id', $params['id'])
                    ->value('name');
                $insert = [
                    'city_code'  => $params['city_code'],
                    'name'       => $name,
                    'village_id' => $params['id'],
                    'itime'      => time()
                ];
                db('hot_vallige')->insert($insert);
            }
            Db::commit();
            return true;
        }
    }

    /**
     * 删除热门小区
     * @param $id
     * @throws Exception
     * @throws PDOException
     */
    public static function del($id) {
        return self::where('village_id', $id)->delete();
    }

}
